package com.bootdo.common.utils;

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;


/**
 * 将多张图片合并转为PDF；需要用到iTextpdf包，
 *
 * @author 浴缸
 */
public class PrintToPdfUtil {
    /**
     * @param pathList 图片文件夹地址
     * @param pdfPath  PDF文件保存地址
     */
    public static void toPdf(String[] pathList, String filePath, String pdfPath) {
        try {
            // 输入流
            FileOutputStream fos = new FileOutputStream(pdfPath);
            // 创建文档
            Document doc = new Document(null, 0, 0, 0, 0);
            // 写入PDF文档
            PdfWriter.getInstance(doc, fos);
            // 读取图片流
            BufferedImage img = null;
            // 实例化图片
            Image image = null;
            // 循环获取图片文件夹内的图片
            for (String imagePath : pathList) {
                String imgSrc = filePath + imagePath.substring("/files/".length());

                //处理图片尺寸
                int lastLength = imgSrc.lastIndexOf(".");
                String subFilePath = imgSrc.substring(0, lastLength);  //得到图片输出路径
                String fileType = imgSrc.substring(lastLength);  //图片类型
                String imgDist = subFilePath + "_600_800" + fileType;
                img = ImageIO.read(new File(imgSrc));
                int w = img.getWidth();
                int h = img.getHeight();
                double r = (double) 595/w;
                double hh = (double) h*r;
                int hhh = (int) Math.round(hh);
                ImageUtils.reduceImg(imgSrc, imgDist, 595, hhh);

                // 读取图片流
                img = ImageIO.read(new File(imgDist));
                // 根据图片大小设置文档大小
                doc.setPageSize(new Rectangle(img.getWidth(), img
                        .getHeight()));
                // 实例化图片
                image = Image.getInstance(imgDist);
                // 添加图片到文档
                doc.open();
                doc.add(image);
            }
            // 关闭文档
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        long time1 = System.currentTimeMillis();
//        toPdf("C:/inspectionReport/20210423/", "C:/inspectionReport/a.pdf");
        long time2 = System.currentTimeMillis();
        int time = (int) ((time2 - time1) / 1000);
        System.out.println("执行了：" + time + "秒！");
    }

}